<template>
    <div class="dh_staff">
        
        <div class="dh_s-content" v-if="pageingstate != 3">
            <!-- 查询 -->
            <div class="dh_s-c-inquire">

                <el-form :model="staffinquire" ref="staffinquire" :inline="true" label-width="70px" class="dh_sci-form mb10 pl10 pr10">
                    <el-form-item label="查询项" class="mt20 mb20">
                        <el-select v-model="staffinquire.select" @change=";for(var r in staffinquire) r != 'select' ? staffinquire[r] = '' : ''">
                            <el-option label="员工姓名" value="1"></el-option>
                            <el-option label="员工ID" value="2"></el-option>
                            <el-option label="员工权限" value="3"></el-option>
                            <el-option label="手机号码" value="4"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="员工姓名" v-if="staffinquire.select === '1'" class="mt20 mb20">
                        <el-input v-model="staffinquire.name" placeholder="请输入查询的员工姓名"></el-input>
                    </el-form-item>

                    <el-form-item label="员工ID" v-else-if="staffinquire.select === '2'" class="mt20 mb20">
                        <el-input v-model="staffinquire.id" placeholder="请输入查询的员工工号"></el-input>
                    </el-form-item>

                    <el-form-item label="员工权限" v-else-if="staffinquire.select === '3'" class="mt20 mb20">
                        <el-select v-model="staffinquire.manage" placeholder="选择查询员工的权限">
                            <el-option label="普通员工" value="0"></el-option>
                            <el-option label="管理员" value="1"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="手机号码" class="mt20 mb20" v-else>
                        <el-input v-model="staffinquire.phone" placeholder="请输入查询的员工手机号"></el-input>
                    </el-form-item>

                    <el-form-item class="mt20 mb20">
                        <el-button type="primary" @click="seekstaff" class="p10 f18">查询</el-button>
                        <el-button type="danger" @click="requeststaff();for(var r in staffinquire) r != 'select' ? staffinquire[r] = '' : ''" class="p10 f18">取消查询</el-button>
                    </el-form-item>
                </el-form>

            </div>
            <!-- 列表数据 -->
            <div class="dh_s-c-list">
                <div class="bb1 mb10 pb10"><button type="button" @click="pageingstate = 3" class="pt5 pr10 pb5 pl10 br5 wh bc4a">添加员工</button></div>
                <table class="dh_scl-table tc f14">
                    <thead>
                        <tr>
                            <th>员工ID</th>
                            <th>员工姓名<br/><span class='n f12 b00a'>*点员工姓名看详情</span></th>
                            <th>登录名称</th>
                            <th>登录密码</th>
                            <th>员工权限</th>
                            <th>手机号</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item,key) in stafflist" :key="key" router to="/sdetails">
                            <td>{{item.id}}</td>
                            <td>
                                <router-link :to="'/sdetails/' + item.id">{{item.name}}</router-link>
                            </td>
                            <td>{{item.username}}</td>
                            <td>{{item.password}}</td>
                            <td>{{item.manage | statemanage}}</td>
                            <td>{{item.phone}}</td>
                            <td>
                                <button type="button" @click="outerVisible=true;for(var i in staffupdata)staffupdata[i]=item[i];staffupdata.key=key" class="wh p10 br5 bc4a">修改</button>
                                <button type="button" @click="staffdelete(item.id,key)" class="wh p10 br5 bcfd">删除</button>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <!-- 分页 -->
                <div class="dh_scl-block bt1 bcwh">
                    <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="currentPage"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pagesize"
                    layout="total, sizes, prev, pager, next"
                    :total="total"
                    class=" pt5 pr10 pb5 pl10">
                    </el-pagination>
                </div>
            </div>
  
            <el-dialog title="修改员工信息" width="35%" top="13%" :center="true" :visible.sync="outerVisible" custom-class="dh_scl-dialog">
                <p class="tc ff53 mb10">*默认值对应的是原始数据，不填写视为不修改</p>
                <el-form :model="staffupdata" class="dialog-form" label-width="70px">
                    <el-form-item label="员工姓名" prop='name'>
                        <el-input type="name" v-model="staffupdata.name" placeholder="请输入新增员工姓名" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="登录名称" prop='username'>
                        <el-input v-model="staffupdata.username" placeholder="请输入登录的用户名" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="登录密码" prop='password'>
                        <el-input v-model="staffupdata.password" placeholder="请输入登录密码" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="" prop='phone'>
                        <label slot="label" class="ws4">手 机 号</label>
                        <el-input v-model="staffupdata.phone" placeholder="请输入新员工的手机号" clearable></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="outerVisible = false">取消</el-button>
                    <el-button type="primary" @click="updatastaff">提交</el-button>
                </div>
            </el-dialog>

        </div>

        <!-- 添加新员工的部分 -->
        <div class="dh_s-addstaff" v-else>
            <div class="bb1 p10"><button type="button" @click="pageingstate = 0" class="wh p5 br5 f14 bc4a mr10">返回列表</button>新增员工</div>
            <el-form :model="staffform" ref="staffform" :rules="rules" label-width="80px" class="dh_s-a-form p20">
                <el-form-item label="员工姓名" prop='name'>
                    <el-col :span="7"><el-input type="name" v-model="staffform.name" placeholder="请输入新增员工姓名" clearable></el-input></el-col>
                </el-form-item>
                <el-form-item label="登录名称" prop='username'>
                    <el-col :span="7"><el-input v-model="staffform.username" placeholder="请输入登录的用户名" clearable></el-input></el-col>
                </el-form-item>
                <el-form-item label="登录密码" prop='password'>
                    <el-col :span="7"><el-input type="password" v-model="staffform.password" placeholder="请输入登录密码" clearable></el-input></el-col>
                </el-form-item>
                <el-form-item label="" prop='phone'>
                    <label slot="label" class="ws4">手 机 号</label>
                    <el-col :span="7"><el-input v-model="staffform.phone" placeholder="请输入新员工的手机号" clearable></el-input></el-col>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="addstaff('staffform')">提交</el-button>
                </el-form-item>
            </el-form>
        </div>

    </div>
</template>

<script>
const axios = require('axios')
export default {
    components: {},
    data() {
        return {
            token: '',
            stafflist: [],
            // 查询的绑定值
            staffinquire:{
                select: '1',
                name: '',
                id: '',
                manage: '',
                phone: ''
            },
            // 添加员工的form表单绑定值
            staffform: {
                name: '',
                username: '',
                password: '',
                phone: ''
            },
            // 添加员工的表单验证
            rules:{
                name:[
                    { required: true, message: '请输入员工姓名', trigger: 'blur' },
                    { min: 2, max: 6, message: '长度在 2 到 4 个字符', trigger: 'blur' }
                ],
                username:[
                    {required: true, message: '请输入登录使用的用户名', trigger: 'blur'}
                ],
                password:[
                    {required: true, message: '请输入登录使用的密码', trigger: 'blur'}
                ],
                phone:[
                    { required: true, message: '请输入员工的手机号码', trigger: 'blur' },
                    { min: 11, max: 11, message: '十一位的数字', trigger: 'blur' }
                ]
            },
            staffupdata:{
                id: '',
                name: '',
                username: '',
                password: '',
                phone: ''
            },
            outerVisible: false,
            innerVisible: false,
            pageingstate: 0,                    //彩笔使用的分页状态管理（区分数据运行）
            currentPage: 1,						//分页的默认页数
            pagesize: 10,                       //单页条数
            total: 0,						   //总条数
        };
    },
    filters: {
        statemanage(manage){
            if(manage===0){
                manage = '普通员工'
            }else{
                manage = '管理员'
            }
            return manage
        }
    },
    computed: {},
    watch: {},
    methods: {
        // 请求列表数据
        requeststaff(){
            let that = this;
            let data = {current:that.currentPage,size:that.pagesize};
            let updata = JSON.stringify(data);
            axios({
                method: 'post',
                url: '/api/staff/list',
                headers:{
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            })
            .then( resp=> {
                // console.log(resp)
                that.pageingstate = 0;
                that.stafflist = resp.data.data
                that.total = resp.data.code;
            })
            .catch( err=> {})
        },

        // 分页的函数
        handleSizeChange(val) {
            // console.log(`每页 ${val} 条`);
            let that = this;
            this.pagesize = val;
            if(that.pageingstate === 0){
                that.requeststaff()
            }else if(that.pageingstate === 1){
                that.seekstaff()
            }else{return}
        },
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            let that = this;
            that.currentPage = val
            if(that.pageingstate === 0){
                that.requeststaff()
            }else if(that.pageingstate === 1){
                that.seekstaff()
            }else{return}
        },

        // 查询搜索
        seekstaff(){
            let that = this;
            if(Number(that.staffinquire.select) === 1 && that.staffinquire.name === ''){
                return that.$message({
                    showClose:true,
                    message: '员工姓名不能为空',
                    type: 'warning'
                })                
            }else if(Number(that.staffinquire.select) === 2 && that.staffinquire.id === ''){
                return that.$message({
                    showClose:true,
                    message: '员工ID不能为空',
                    type: 'warning'
                })              
            }else if(Number(that.staffinquire.select) === 3 && that.staffinquire.manage === ''){
                return that.$message({
                    showClose:true,
                    message: '员工权限不能为空',
                    type: 'warning'
                })              
            }else if(Number(that.staffinquire.select) === 4 && that.staffinquire.phone === ''){
                return that.$message({
                    showClose:true,
                    message: '员工的手机号不能为空',
                    type: 'warning'
                })              
            }else{
                let data = {current:that.currentPage,size:that.pagesize};
                for(var i in that.staffinquire){
                    that.staffinquire[i] !== '' && i !== "select" ? data[i] = that.staffinquire[i] : '';
                }
                let updata = JSON.stringify(data);
                // console.log(updata)
                axios({
                method: 'post',
                url: '/api/staff/list',
                headers:{
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
                })
                .then( resp=> {
                    // console.log(resp)
                    that.pageingstate = 1;
                    that.stafflist = resp.data.data
                    that.total = resp.data.code;
                    this.$message({
                        showClose: true,
                        message: '搜索到'+resp.data.code+'条数据',
                        type: 'success'
                    })
                })
                .catch( err=> {})
            }
        },

        // 添加新员工
        addstaff(formverify){
            let that = this;
            that.$refs[formverify].validate((valid)=>{
                if(valid){
                    let data = {};
                    // 表单对象与上传字段相同，for in循环赋值加去除空值
                    for(var o in that.staffform)
                    that.staffform[o] !== '' ? data[o] = that.staffform[o] : delete data[o]
                    let updata = JSON.stringify(data)
                    // console.log(updata)
                    axios({
                        method: 'post',
                        url: '/api/staff/add',
                        headers:{
                            'Content-type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: updata
                    }).then( resp=> {
                        // console.log(resp)
                        if(/^[0-9]*$/.test(resp.data.data)){
                            that.stafflist.length < that.pagesize ? that.stafflist.push(data) : '';
                            for(var y in that.staffform) that.staffform[y] = '';
                            that.pageingstate = 0
                            that.total += 1;
                        }else{return}
                    }).catch( err=> {})
                    that.$message({
                        showClose: true,
                        message: '添加成功，可以在员工列表中找到该员工的信息',
                        type: 'success'
                    })
                }else{
                    return false
                }
            })
        },

        // 修改员工数据
        updatastaff(){
            let that = this;
            let data = {}
            for(var o in that.staffupdata)
            o!="key" && that.staffupdata[o]!=='' ? data[o] = that.staffupdata[o] : delete data[o];
            let updata = JSON.stringify(data)
            this.$confirm('请再确认一下提交信息，无误后点击提交即可完成修改','提示',{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(()=>{
                that.outerVisible = false
                axios({
                    method: 'post',
                    url: '/api/staff/update',
                    headers:{
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=>{
                    // console.log(resp)
                    for(var t in data)
                    that.stafflist[that.staffupdata.key][t] = data[t]
                }).catch(err=>{})
                this.$message({
                    type: 'success',
                    message: '修改成功'
                })
            }).catch(()=>{
                this.$message({
                    type: 'info',
                    message:'已取消修改'
                })
            })
        },

        // 删除
        staffdelete(id,key){
            let that = this;
            let data = {id: id};
            let updata = JSON.stringify(data);
            this.$confirm('删除员工后相应的数据页无法找到，确定要删除吗？','提示',{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(()=>{
                axios({
                    method: 'post',
                    url: '/api/staff/delete',
                    headers: {
                        'Content-type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=> {
                    // console.log(resp)
                    if(resp.data.data === "删除成功！"){
                        that.stafflist.splice(key,1);
                        that.total--
                        that.stafflist.length === 0 ? (that.currentPage-=1,that.requeststaff()) : '';
                    }else{return}
                }).catch( err=> {})
                this.$message({
                    type: 'success',
                    message: '成功删除'
                })
            }).catch(()=>{
                this.$message({
                    type: 'info',
                    message:'已取消删除'
                })
            })
        },

        // 刷新请求token
        async requesttoken(){
            let that = this;
            let loguser = JSON.parse(sessionStorage.getItem('updata'))
            let data = {username:loguser.username, password:loguser.password};
            let updata = JSON.stringify(data);
            // console.log(updata)
            await axios({
                method: 'post',
                url: '/api/getAuthority/manager',
                headers: { 'Content-Type': 'application/json' },
                data: updata
            })
            .then( resp=> {
                // console.log(resp)
                that.token = resp.data.data;
                sessionStorage.setItem('token',JSON.stringify(resp.data.data))
                that.requeststaff()
            }).catch( err=> {})
        }
    },
    created() {
        this.requesttoken()
    },
    mounted() {
        let that = this;
        // that.token = JSON.parse(sessionStorage.getItem('token'))
        // that.requeststaff()
    },
    beforeCreate() {},
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    }
</script>
<style scoped>
.dh_staff{
    height: 100%;
}
.dh_s-content{
    height: 100%;
}
/* 查询 */
.dh_sci-form{
    background-color: #ffffff;
    box-shadow: 0 0 2px #4b4b4b;
    border-radius: 5px;
}
/* 列表数据 */
.dh_s-c-list{
    display: flex;
    flex-direction: column;
    height: calc(100% - 91px);
    padding: 10px;
    background-color: #ffffff;
    border-radius: 5px;
    box-sizing: border-box;
    box-shadow: 0 0 2px #4b4b4b;
}
.dh_scl-table{
    width: 100%;
    border-collapse: collapse;
    border-bottom: 1px solid #e0e0e0;
    border-right: 1px solid #e0e0e0;
    border-spacing: 0;/*去掉单元格间隙*/
}
.dh_scl-table th{
    background-color: #ececec;
}
.dh_scl-table tbody tr:hover{
    background-color: #ececec;
}
.dh_scl-table th,.dh_scl-table td{
    padding: 10px 0;
    border-left:1px solid #e0e0e0;
    border-top:1px solid #e0e0e0;
}
/* 分页 */
.dh_scl-block{
    margin-top: auto;
}

/* 加员工 */
.dh_s-addstaff{
    /* height: 100%; */
    background-color: #ffffff;
    border-radius: 5px;
    box-shadow: 0 0 3px #3d3d3d;
}
.el-form-item__label{
    border-bottom: 1px solid #e7e7e7;
}

</style>
<style>
/* .dh_scl-dialog .el-dialog--center .el-dialog__body{
    padding: 0 30px;
}
.dh_scl-dialog .el-dialog__body{
    padding: 0;
} */
</style>